package com.jmp.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.jmp.api.service.CompanyAccountService;
import com.jmp.base.PayApi;
import com.jmp.base.dto.PayWxCashRequest;
import lombok.extern.slf4j.Slf4j;
import one.stand.config.WxUrlConfig;
import one.stand.enums.LoginEnum;
import one.stand.exception.GoPayException;
import one.stand.model.CompanyAccount;
import one.stand.model.ResultModel;
import one.stand.util.WxConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class PayController implements PayApi {
    /**
     * 成功码
     */
    public final static String SUCCESS = "SUCCESS";

    /**
     * 自定义参数，可以为终端设备号(门店号或收银设备ID)，PC网页或公众号内支付可以传"WEB"
     */
    private final static String deviceInfo = "";

    /**
     * 符合ISO 4217标准的三位字母代码，默认人民币：CNY
     */
    private final static String fee_type = "CNY";

    /**
     * JSAPI：JSAPI支付 NATIVE：Native支付 APP：APP支付
     */
    private final static String trade_type = "JSAPI";

    /**
     * 微信提现请求Url
     */
    private final static String transfers = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";

    @Autowired
    private WxUrlConfig wxUrlConfig;

    @Autowired
    private CompanyAccountService companyAccountService;

    @Override
    public ResultModel wxCash(@RequestBody PayWxCashRequest request) {
        log.info("微信提现接口参数：{}", JSONObject.toJSONString(request));
        if (StringUtils.isEmpty(request.getOpenid()) || StringUtils.isEmpty(request.getCompanyKey()) || request.getAmount() == null) {
            return ResultModel.checkParamFail();
        }
        try {
            WxConfig wxConfig = wxConfig(request.getCompanyKey());
            WXPay wxpay = new WXPay(wxConfig);
            Map<String, String> data = new HashMap<>(10);
            data.put("mch_appid", wxConfig.getAppID());
            data.put("mchid", wxConfig.getMchID());
            data.put("nonce_str", getRandomNumber());
            data.put("partner_trade_no", request.getRecordNo());
            data.put("openid", request.getOpenid());
            data.put("check_name", "NO_CHECK");
            data.put("amount", String.valueOf(request.getAmount()));
            data.put("desc", "微信提现");
            data.put("spbill_create_ip", request.getIp());
            String sign = WXPayUtil.generateSignature(data, wxConfig.getKey());
            data.put("sign", sign);
            String str = wxpay.requestWithCert(transfers, data, 60000, 60000);
            log.info("微信提現返回：{}" + str);
            Map<String, String> resp = wxpay.processResponseXml(str);
            if (SUCCESS.equals(resp.get("return_code"))) {
                if (SUCCESS.equals(resp.get("result_code"))) {
                    return ResultModel.success(resp);
                }
            }
            return ResultModel.fail(resp.get("err_code_des"));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultModel.fail(e.getMessage());
        }
    }

    /**
     * 随机数
     */
    private static String getRandomNumber() {
        return System.currentTimeMillis() + "" + (int) (1 + Math.random() * (9999));
    }


    private WxConfig wxConfig(String companyKey) throws GoPayException {
        CompanyAccount companyAccountModel = companyAccountService.getDefaultIfNull(companyKey, LoginEnum.WX_PAY);
        if (null == companyAccountModel) {
            log.info("未获取到公司账户{}", companyKey);
            throw new GoPayException("未获取到公司账户~!");
        }
        if (companyAccountModel.getState() != 1) {
            log.info("公司账户认证未成功{}", JSON.toJSONString(companyAccountModel));
            throw new GoPayException("公司账户认证未成功~!");
        }
        WxConfig wxConfig = new WxConfig();
        wxConfig.setAppId(companyAccountModel.getAppId());
        wxConfig.setKey(companyAccountModel.getKey());
        wxConfig.setMchId(companyAccountModel.getMerchantId());
        wxConfig.setCertData(Base64.getDecoder().decode(companyAccountModel.getCertData()));
        wxConfig.setNotifyUrl(wxUrlConfig.getNotifyUrl());
        wxConfig.setRefundUrl(wxUrlConfig.getRefundUrl());
        wxConfig.setHttpConnectTimeoutMs(5000);
        wxConfig.setHttpReadTimeoutMs(5000);
        return wxConfig;
    }

}
